package com.itany.websocket.websocket.controller;

import com.itany.websocket.websocket.websocket.SpringWebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public String login(String nickname, HttpSession session)throws Exception {
        System.out.println("UserController.login()");

        System.out.println("nickname = " + nickname);

        session.setAttribute("nickname",nickname);

        Map<String, WebSocketSession> users= SpringWebSocketHandler.users;

        for (String name : users.keySet()) {
            synchronized (this){
                //服务器向客户端推送消息
            }
            users.get(name).sendMessage(new TextMessage(nickname+"进入聊天室 "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        }

        return "talk";
    }

    @RequestMapping("/send")
    public @ResponseBody String send()throws Exception {
        System.out.println("UserController.send()");

        Map<String, WebSocketSession> users= SpringWebSocketHandler.users;

        for (String name : users.keySet()) {
            synchronized (this){
                //服务器向客户端推送消息
                users.get(name).sendMessage(new TextMessage("UserController发送的消息 "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            }
        }

        return "<h1>发送成功</h1>";
    }
}
